import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/class_course_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/user_select_sort_save_response_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../update_task_view_model.dart';

class PersonalClassWidget extends StatefulWidget {
  final FaceUserInfoBean infoBean;
  final String pages;

  const PersonalClassWidget({Key key,this.infoBean, this.pages})
      : super(key: key);

  @override
  _PersonalClassWidgetState createState() => _PersonalClassWidgetState();

  ///跳转方法
  static Future<List<ClassCourseListItemBean>> navigatorPush(
      BuildContext context, FaceUserInfoBean infoBean,String pages) {
    return RouterUtils.routeForFutureResult<List<ClassCourseListItemBean>>(
      context,
      PersonalClassWidget(
        infoBean: infoBean,
        pages: pages,
      ),
    );
  }
}

class _PersonalClassWidgetState extends BaseState<PersonalClassWidget> {
  List<ClassCourseListItemBean> mList;
  final String _classType = "03";
  // bool isLightUp = false; //确认按钮是否亮起
  List<String> selectCourseIndex = new List(); //选中的行
  List<String> cacheLastClass = new List(); //上次选中的班级id


  List<TextEditingController> _editCourseListController =
      new List<TextEditingController>();
  //确定保存接口列表
  List<ClassCourseListItemBean> listClassItemBean = new List();

  // TextEditingController _editCourseController;
  // List<ClassCourseListItemBean> mAddRecordClassList = List();
  CommonListPageWidgetState mState;

  List<ClassCourseListItemBean> selectListCourseItemBean;
  String roleId = UserRepository.getInstance()?.userData?.comUser?.roleid;
  UpdateTaskViewModel viewModel;

  //置顶新列表
  // List<ClassCourseListItemBean> topSelectListCourseItemBean = new List();

  String cacheKey;

  String searchName;
  @override
  void initState() {
    super.initState();
    mList = List<ClassCourseListItemBean>();
    selectListCourseItemBean = new List();
    viewModel = UpdateTaskViewModel(this);
    if(widget?.infoBean!=null && widget?.infoBean?.showClassInfo!=null){
      selectCourseIndex =
          (widget?.infoBean?.showClassInfo ?? []).map((e) => e.classid).toList();
    }
    cacheKey=KEY_SELECT_CLASS +
        UserRepository.getInstance().getCacheKeySuffix();
    SharePreferenceUtil.getStringList(cacheKey
    ).then((value) {
      if(value!=null){
        cacheLastClass =value;
        setState(() {
        });
      }else  if(widget?.infoBean!=null && widget?.infoBean?.showClassInfo!=null){
        cacheLastClass = selectCourseIndex;
      }
    });

    // checkSave();
  }

  @override
  Widget build(BuildContext context) {
    // List<String> list = List<String>();
    // widget?.infoBean?.showClassInfo?.forEach((element) {
    //   list?.add(element?.classid);
    // });
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            // color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            _toTopBarWidget(),
            // if(AppOverallDistinguish.comefromAiOrWeStudy())
            Padding(
              padding: const EdgeInsets.only(left: 7, right: 7, top: 10,bottom: 10),
              child: _searchDepartmentWidget(),
            ),
            // SizedBox(
            //   height: 10,
            // ),
            if (roleId == "99" && AppOverallDistinguish.comefromAiOrWeStudy())
              //点击添加一行
              _addCourseListWidget(),
            //课程list
            _courseClassListWidget(),
          ],
        ),
      ),
    );
  }

  // bool _showSearchBar(){//添加不展示
  //   if(widget?.pages!="CreateUserPage"){
  //     return true;
  //   }
  //   return false;
  // }

  Widget _courseClassListWidget() {
    return Expanded(
      child: CommonListPageWidget<ClassCourseListItemBean, ClassCourseBean>(
        enablePullUp: false,
        enablePullDown: true,
        queryMapFunc: (int page) => {
          "authId": UserRepository.getInstance().authId ?? "",
          "name": searchName??"",
          "type": _classType,
        },
        parseDataFunc: (VgHttpResponse resp) {
          loading(false);
          ClassCourseBean bean = ClassCourseBean.fromMap(resp?.data);
          bean?.data?.removeWhere((element) =>
              element == null ||
              StringUtils.isEmpty(element.id) ||
              StringUtils.isEmpty(element.name));
          if(cacheLastClass!=null&&cacheLastClass.length>0&&bean.data!=null&&bean.data.length>0){
            List<ClassCourseListItemBean> newList=List();
            for (ClassCourseListItemBean element in bean.data) {
              if (cacheLastClass.contains(element.id)) {
                newList.insert(0, element);
              }else{
                if(AppOverallDistinguish.comefromAiOrWeStudy()){
                  newList.add(element);
                }
              }
            }
            bean.data=newList;
          }
          return bean;
        },
        listFunc: (List<ClassCourseListItemBean> courseList) {
          if (selectCourseIndex == null || selectCourseIndex.isEmpty) {
            return;
          }
          for (ClassCourseListItemBean itemBean in courseList) {
            if (itemBean?.id == null || itemBean.id.isEmpty) {
              continue;
            }
            if (selectCourseIndex.indexOf(itemBean.id) != -1) {
              itemBean.isSelect = true;

              List<String> selectListIds = List<String>();
              selectListCourseItemBean?.forEach((element) {
                selectListIds?.add(element?.id);
              });
              if(!(selectListIds?.toString()?.contains(itemBean?.id)??false)){
                selectListCourseItemBean.add(itemBean);
              }
            }
          }
          courseList.forEach((element) {
            if(element.isSelect ?? false){
              mList?.insert(0, element);
            }else{
              mList?.add(element);
            }
          });


          if (_editCourseListController == null ||
              _editCourseListController.isEmpty) {
            return;
          }
          _editCourseListController?.forEach((controller) {
            ClassCourseListItemBean addItemBean = ClassCourseListItemBean();
            addItemBean.isEdit = true;
            addItemBean.controller = controller;
            mList?.insert(0, addItemBean);
          });
        },
        stateFunc: (CommonListPageWidgetState state) {
          mState = state;
        },
        itemBuilder: (BuildContext context, int index,
            ClassCourseListItemBean itemBean) {
          if (itemBean == null) return Container();

          if (itemBean?.isEdit ?? false) {
            return _addCourseListRow(context, index, itemBean);
          }

          return _toListItemWidget(context, index, itemBean);
        },
        //分割器构造器
        separatorBuilder: (context, int index, _) {
          return Container(
            height: 0.5,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            padding: const EdgeInsets.only(left: 15),
            child: Container(
              color: Color(0xFF303546),
            ),
          );
          // return divider;
        },
        placeHolderFunc: (List<ClassCourseListItemBean> list, Widget child,
            VoidCallback onRefresh) {
          return VgPlaceHolderStatusWidget(
            emptyStatus: list == null || list.isEmpty,
            emptyOnClick: () => onRefresh(),
            child: child,
          );
        },
        netUrl:ServerApi.BASE_URL + "app/appChooseInfo",
        httpType: VgHttpType.post,
      ),
    );
  }

  Widget _addCourseListRow(
      BuildContext context, int index, ClassCourseListItemBean itemBean) {
    return GestureDetector(
      onTap: () {
        if (itemBean?.isSelect == null || itemBean?.isSelect == "")
          itemBean?.isSelect = false;
        itemBean?.isSelect = !(itemBean?.isSelect??false);
        setState(() {});
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 10,
            ),
            Image(
              image: itemBean?.isSelect ?? false
                  ? AssetImage("images/common_unselect_ico.png")
                  : AssetImage("images/common_selected_ico.png"),
              width: 20,
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: VgTextField(
                autofocus: true,
                maxLines: 1,
                controller: itemBean.controller,
                onChanged: (String editCourse) {
                  // itemBean?.name= _editCourseController?.text;
                  // print("输出长度：${_editCourseListController.length}");
                  String editListText = "";
                  for (TextEditingController item
                      in _editCourseListController) {
                    editListText += item.text.toString();
                  }
                  // if (_editCourseListController.length != 0 &&
                  //     editListText.trim() != null &&
                  //     editListText.trim() != "") {
                  //   isLightUp = true;
                  // }
                  setState(() {});
                },
                decoration: InputDecoration(
                  border: InputBorder.none,
                  counterText: "",
                  contentPadding: const EdgeInsets.only(bottom: 2),
                  hintText: "请输入班级名",
                  hintStyle: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getTextEditHintColor_3A3F50(),
                      fontSize: 14),
                ),
                style: TextStyle(
                    fontSize: 14,
                    color: ThemeRepository.getInstance()
                        .getTextMainColor_D0E0F7()),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, ClassCourseListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        if(!AppOverallDistinguish.comefromAiOrWeStudy()){
          VgToastUtils.toast(context, "请至蔚来一起学设置");
          return;
        }
        itemBean.isSelect = !(itemBean.isSelect??false);
        if (itemBean.isSelect) {
          List<String> listSelectIds = List<String>();
          selectCourseIndex?.forEach((element) {//map容易出错
            listSelectIds?.add(element);
          });
          if(!(listSelectIds?.toString()?.contains(itemBean.id)??false)){
            selectCourseIndex.add(itemBean.id);
          }
          List<String> selectListIds = List<String>();
          selectListCourseItemBean?.forEach((element) {
            selectListIds?.add(element?.id);
          });
          if(!(selectListIds?.toString()?.contains(itemBean.id)??false)){
            selectListCourseItemBean.add(itemBean);
          }

        } else {
          selectCourseIndex.remove(itemBean.id);
          ClassCourseListItemBean bean = ClassCourseListItemBean();
          selectListCourseItemBean?.forEach((element) {
            if((element?.id?.contains(itemBean.id)??false)){
              bean = element;
            }
          });
          selectListCourseItemBean.remove(bean);
        }
        setState(() {
          // checkSave();
        });
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 10,
            ),
            Image(
              image: itemBean.isSelect ?? false
                  ? AssetImage("images/common_selected_ico.png")
                  : AssetImage("images/common_unselect_ico.png"),
              width: 20,
            ),
            SizedBox(
              width: 10,
            ),
            Container(
              width: (VgToolUtils.getScreenWidth()/4)*3,
              child: Text(
                itemBean?.name ?? "",
                style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _editCourseWidget() {
    return Container(
      height: 50,
      color: Colors.redAccent,
      child: VgTextField(),
    );
  }

  Widget _addCourseListWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        _addRowCourse();
      },
      child: Container(
        height: 50,
        padding: const EdgeInsets.only(left: 7),
        alignment: Alignment.centerLeft,
        child: Text(
          "+添加",
          style: TextStyle(color: Color(0xFF1890FF), fontSize: 14),
          textAlign: TextAlign.left,
        ),
      ),
    );
  }

  void _addRowCourse() {
    TextEditingController _editCourseController = new TextEditingController();
    ClassCourseListItemBean addItemBean = ClassCourseListItemBean();
    addItemBean.isEdit = true;
    addItemBean.controller = _editCourseController;

    _editCourseListController.insert(0, _editCourseController);
    mList?.clear();
    mState?.data?.forEach((element) {
      mList?.add(element);
    });
    mList?.insert(0, addItemBean);
    mState?.data = mList;
    // mAddRecordClassList.add(addItemBean);
    mState.setState(() {});
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "班级",
      rightWidget: _buttonWidget(),
      isHideRightWidget: !AppOverallDistinguish.comefromAiOrWeStudy(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 48,
        height: 24,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          _httpSave();
          // if (isLightUp) {
          //   _httpSave();
          // }
        },
      ),
    );
  }

  void _httpSave() {
    //判断是否有新增的班级
    if (_editCourseListController != null &&
        _editCourseListController?.length > 0) {
      String textList = "";
      List<String> classTextList = new List();
      //判断是否是空格，remove
      _editCourseListController?.forEach((element) {
        if (element?.text?.trim() == "") {
          _editCourseListController.remove(element);
        }
        classTextList?.add(element?.text?.trim());
      });
      textList = VgStringUtils?.getSplitStr(classTextList, symbol: ",");

      //如果有新增但是班级为空
      if (textList == "") {
        return;
      }
      VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo",
          params: {
            "authId": UserRepository.getInstance().authId ?? "",
            "name": textList ?? "",
            "type": _classType,
          },
          callback: BaseCallback(onSuccess: (dynamic val) async{
            UserSelectSortSaveResponseBean successBean =
                UserSelectSortSaveResponseBean.fromMap(val);
            if (successBean == null ||
                successBean.data == null ||
                successBean.data.isEmpty) {
              VgToastUtils.toast(context, "课程添加返回值错误");
              return;
            }
            VgEventBus.global.send(new RefreshPersonDetailEvent());
            String classId = "";
            List<String> classIdList = new List();
            //返回新增的数据
            successBean.data.forEach((element) {
              ClassCourseListItemBean classCourseListItemBean =
                  ClassCourseListItemBean();
              classCourseListItemBean?.name = element?.name;
              classCourseListItemBean?.id = element?.id;
              classIdList?.add(element?.id);
              listClassItemBean.add(classCourseListItemBean);
            });
            List<String> list = List<String>();
            //返回选中的数据
            if (selectListCourseItemBean?.length != 0 &&
                selectListCourseItemBean != null) {
              widget?.infoBean?.classInfo?.forEach((element) {
                list?.add(element?.classid);
              });
              selectListCourseItemBean?.forEach((element) {
                listClassItemBean.add(element);
                classIdList?.add(element?.id);
                widget?.infoBean?.showClassInfo?.forEach((classId) {
                  if(!(classId?.classid?.contains(element?.id))){
                    list?.remove(classId?.classid);
                  }
                });
                // if(!(widget?.infoBean?.showClassInfo?.map((e) => e?.classid?.toString())?.contains(element?.id))){
                //   list?.remove(element?.id);
                // }
                if(!(list?.contains(element?.id)??false)){
                  list?.add(element?.id);
                }
              });
            }
            classId = VgStringUtils?.getSplitStr(classIdList, symbol: ",");
            //接收数据，selectCourseIndex进行for循环对比，拿出选中的指返回给上一界面
            // VgToastUtils.toast(context, "保存成功");
            // _toUpdateChooseInfo(VgStringUtils?.getSplitStr(list, symbol: ","));
            _toUpdateChooseInfo(classId);
          }, onError: (String e) {
            VgToastUtils.toast(context, "添加数据错误");
            return;
          }));
    } else {
      //没有新增班级
      popResult();
    }
  }

  ///返回选择结果
  void popResult() {
    String classText = "";
    List<String> classTextList = new List();
    cacheLastClass.clear();
    List<String> list = List<String>();
    if (selectListCourseItemBean?.length != 0 &&
        selectListCourseItemBean != null) {
      widget?.infoBean?.classInfo?.forEach((element) {
        list?.add(element?.classid);
      });
      selectListCourseItemBean?.forEach((element) {
        listClassItemBean.add(element);
        classTextList?.add(element?.id);
        widget?.infoBean?.showClassInfo?.forEach((classId) {
          if(!(classId?.classid?.contains(element?.id))){
            list?.remove(classId?.classid);
          }
        });
        if(!(list?.contains(element?.id)??false)){
          list?.add(element?.id);
        }
      });
    }

    if(UserRepository.getInstance().userData.comUser.roleid=="90"){
      classText = _toUpdateChooseInfo(VgStringUtils?.getSplitStr(list, symbol: ","));
    }else{
      classText = VgStringUtils?.getSplitStr(classTextList, symbol: ",");
    }
    _toUpdateChooseInfo(classText);
  }

  _toUpdateChooseInfo(String classText){
    viewModel?.batchAppUpdateChooseInfo(
        context, widget?.infoBean?.fuid, "", classText, "", "", "",pageNames: widget?.pages);
    if(widget?.infoBean?.isSelectAll??false){
      //ClassOrDepartmentPage
      RouterUtils.popUntil(context, "ClassOrDepartmentPage");
    }else{
      cacheLastClass=listClassItemBean.map((e) => e.id).toList();
      SharePreferenceUtil.putStringList(cacheKey, cacheLastClass);
      RouterUtils.pop(context, result: listClassItemBean);
    }
    VgToastUtils.toast(context, "设置成功");
    }


  Widget _searchDepartmentWidget() {
    return Container(
      height: 30,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        contentPadding: EdgeInsets.only(top: 0, bottom: 15),
        hintText: "搜索",
        customIcon: "images/common_search_ico.png",
        iconColor: Colors.white54,
        onChanged: (String classText) {
          searchName = classText;
          mState?.viewModel?.refresh();
        },
      ),
    );
  }

  // void checkSave() {
  //   isLightUp =
  //       selectListCourseItemBean.isNotEmpty || selectCourseIndex.isNotEmpty;
  // }
}
